/**
 * Check if an element has a class
 * @param {HTMLElement} ele
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele: HTMLElement, cls: string) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function addClass(ele: HTMLElement, cls: string) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function removeClass(ele: HTMLElement, cls: string) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * 判断是否是外部链接
 *
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
  return isExternal;
}

// 格式化金额为千位分隔符形式
export function formatCurrency(value: string | number) {
  if (value === null || value === undefined || value === "") {
    return "";
  }
  const num = parseFloat(value.toString());
  if (isNaN(num)) {
    return "";
  }
  return num.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

// 格式化身份证号码
export function formatIdNumber(idNumber: string) {
  if (!idNumber) return "111111111111111111"; // 默认值
  return idNumber.slice(0, 6) + "********" + idNumber.slice(-4);
}

// 格式化日期
export function formatDate(date: string) {
  if (!date) return ""; // 如果日期为空，返回空字符串
  const dateObj = new Date(date);
  const year = dateObj.getFullYear();
  const month = dateObj.getMonth() + 1; // 月份从0开始，需要加1
  const day = dateObj.getDate(); // 日期
  return `${year}年${month}月${day}日`;
}
